require "utils"
require "pm"
require "pins"
require "aLiCMD"
require "hwCMD"

module(..., package.seeall)

local get_power = pins.setup(pio.P0_25)

function return_power()
    return get_power()
end

-- 断电报警任务
sys.taskInit(function()
    while true do
        sys.wait(10)
        -- log.info("POWER", get_power())
        -- 断电
        if get_power() == 0 and nvm.get("POWER_STATE") == false then
            sys.wait(5000)
            if get_power() == 0 and nvm.get("POWER_STATE") == false then
                aLiCMD.eventPost("POWER OFF")
                aLiCMD.poweroff()

                hwCMD.hwAlarm(config.HW_ENV_PRODUCT_KEY .. "_" .. string.sub(misc.getImei(), -6, -1) .. "_ENV",
                        "POWER_STATE",
                        "POWER_OFF",
                        0)
                if hwIotda.isReady() then
                    nvm.set("POWER_STATE", true)
                end

                sys.publish("POWER_STATE", 1)
            end
            --    断电恢复
        elseif get_power() == 1 and nvm.get("POWER_STATE") == true then
            sys.wait(5000)
            if get_power() == 1 and nvm.get("POWER_STATE") == true then
                aLiCMD.eventPost("POWER ON")
                aLiCMD.onceStart()

                hwCMD.hwAlarm(config.HW_ENV_PRODUCT_KEY .. "_" .. string.sub(misc.getImei(), -6, -1) .. "_ENV",
                        "POWER_STATE",
                        "POWER_ON",
                        1)
                if hwIotda.isReady() then
                    nvm.set("POWER_STATE", false)
                end

                sys.publish("POWER_STATE", 0)
            end
        end
    end
end)
